package com.sjtu.rest;

import com.sjtu.constants.ApiConstants;
import com.sjtu.form.JobInvokeForm;
import com.sjtu.zookeeper.InstanceDetails;
import com.sjtu.zookeeper.ServiceDiscoverUtil;
import org.apache.curator.x.discovery.ServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * nerine
 * 2/6/2020
 */
@RestController
public class DemoRest {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private WebClient webClient;
    @Autowired
    private ApplicationContext context;

    @GetMapping("/test/task")
    public short sendTask() throws Exception {
        //do lock
        //
        ServiceProvider<InstanceDetails> provider =
                ServiceDiscoverUtil.getServiceProvider("DEMO-CLIENT");
        System.out.println(provider.getAllInstances());
        JobInvokeForm form = new JobInvokeForm(UUID.randomUUID().toString(),
                "DEMO-CLIENT",
                "123");
        Mono<JobInvokeForm> mono = Mono.just(form);
        mono.subscribe(onInvoke -> {
            System.out.println("onInvoke");
        }, error -> {
            System.out.println("error");
            error.printStackTrace();
        }, () -> {
            System.out.println("complete");
        });


        try {
            Mono<Short> result = webClient.post()
                    .uri(
                            concatHttpUrl(provider.getInstance().getAddress(), provider.getInstance().getPort()) +
                                    ApiConstants.CLIENT_INVOKE_URL

                    )
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(mono, JobInvokeForm.class)
                    .retrieve()
                    .bodyToMono(Short.class);
            return result.block().shortValue();
        }catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    String concatHttpUrl(String ip, int port) {
        return "http://" + ip + ":" + port;
    }
}
